import { useModel } from "umi";
import { useReactive } from "ahooks";
import { useEffect } from "react";
import { Space, Table, Card, Popconfirm, Divider, message } from "antd";
import { Button } from "@douyinfe/semi-ui";

import { UpdateDependentedDatabases } from "../../_graphql/organizations";

const DependentedDatabases = ({ dependentedDatabases, loadOrganizationBaseInfo }) => {
    const { graphqlFetchPlatform, BNTApplicationResourceCenterServiceURL, remoteData } = useModel("global");
    const { setModalVisible, setModalTitle, setModalWidth, setModalComponent } = useModel("global.modal");
    const { currentOrganizationUuid } = useModel("organization.info");

    const state = useReactive({
        loading: false,
        submitLoading: false,
        data: [],
    });

    const addInitDatabases = async () => {
        let res = await remoteData({
            object: "bnt-application-resource-center-service",
            serviceUrl: BNTApplicationResourceCenterServiceURL,
            serviceName: "/resource/referenceDatabase/organization/getAll",
            params: {},
        });
        if (res) {
            res = await graphqlFetchPlatform({
                query: UpdateDependentedDatabases,
                variables: {
                    uuid: currentOrganizationUuid,
                    dependentedDatabases: res?.filter((item) => item.isInit === true) || [],
                },
            });
            if (res) {
                message.success("成功更新组织依赖的数据库模型信息");
                loadOrganizationBaseInfo();
            }
        }
    };

    const openAddDatabaseModal = async () => {
        setModalTitle("添加依赖的数据库");
        setModalWidth(750);
        setModalComponent(<AddDependentedDatabase dependentedDatabases={dependentedDatabases} loadOrganizationBaseInfo={loadOrganizationBaseInfo} />);
        setModalVisible(true);
    };

    const deleteData = async (record) => {
        state.submitLoading = true;
        let data = dependentedDatabases.filter((item) => item.uuid !== record.uuid);
        let res = await graphqlFetchPlatform({
            query: UpdateDependentedDatabases,
            variables: {
                uuid: currentOrganizationUuid,
                dependentedDatabases: data,
            },
        });
        if (res) {
            loadOrganizationBaseInfo();
        }
        state.submitLoading = false;
    };

    return (
        <Card
            title="依赖的数据库模型"
            bodyStyle={{ padding: 0 }}
            extra={
                <Space>
                    {currentOrganizationUuid && <Button onClick={addInitDatabases}>添加初始的数据库</Button>}
                    {currentOrganizationUuid && <Button onClick={openAddDatabaseModal}>添加依赖的数据库</Button>}
                </Space>
            }
        >
            <Table loading={state.loading} dataSource={dependentedDatabases} size="small" bordered={false} pagination={false} rowKey="uuid" style={{ paddingTop: 1 }}>
                <Table.Column title="序号" align="center" width={60} render={(_, r, i) => i + 1} />
                <Table.Column title="参考数据库名称" dataIndex="databaseName" align="left" />
                <Table.Column title="参考数据库说明" dataIndex="title" align="left" />
                <Table.Column
                    title="操作"
                    align="center"
                    width={120}
                    render={(_, r) => (
                        <Space size={0} split={<Divider type="vertical" />}>
                            {r.isInit === false && (
                                <Popconfirm
                                    title="确认要移除该依赖的数据库信息吗?"
                                    okButtonProps={{
                                        loading: state.submitLoading,
                                    }}
                                    placement="topRight"
                                    onConfirm={() => deleteData(r)}
                                >
                                    <a>移除</a>
                                </Popconfirm>
                            )}
                        </Space>
                    )}
                />
            </Table>
        </Card>
    );
};

const AddDependentedDatabase = ({ dependentedDatabases, loadOrganizationBaseInfo }) => {
    const { graphqlFetchPlatform, remoteData, BNTApplicationResourceCenterServiceURL } = useModel("global");
    const { currentOrganizationUuid } = useModel("organization.info");
    const { onCloseGlobalModal } = useModel("global.modal");

    const state = useReactive({
        loading: false,
        data: [],
    });

    const loadData = async () => {
        state.loading = true;
        let res = await remoteData({
            object: "bnt-application-resource-center-service",
            serviceUrl: BNTApplicationResourceCenterServiceURL,
            serviceName: "/resource/referenceDatabase/organization/getAll",
            params: {},
        });
        state.data = res.filter((item) => dependentedDatabases.findIndex((_item) => _item.uuid === item.uuid) === -1) || [];
        state.loading = false;
    };

    useEffect(() => {
        loadData();
    }, []);

    const add = async (record) => {
        dependentedDatabases.push(record);
        let res = await graphqlFetchPlatform({
            query: UpdateDependentedDatabases,
            variables: {
                uuid: currentOrganizationUuid,
                dependentedDatabases,
            },
        });
        if (res) {
            message.success("成功更新组织依赖的数据库模型信息");
            await loadOrganizationBaseInfo();
            await loadData();
            onCloseGlobalModal();
        }
    };

    return (
        <Table loading={state.loading} dataSource={state.data} size="small" bordered pagination={false} rowKey="uuid">
            <Table.Column title="参考数据库名称" dataIndex="databaseName" align="left" />
            <Table.Column title="参考数据库说明" dataIndex="title" align="left" />
            <Table.Column title="操作" align="center" render={(_, r) => <a onClick={() => add(r)}>选择</a>} />
        </Table>
    );
};

export default DependentedDatabases;
